<?php
/**
 * Author: xx.com
 */ 
namespace Api\Controller;
use Home\Logic\GoodsLogic;
use Think\Page;
class GoodsController extends BaseController {
    
    /**
     * 析构流函数
     */
    public function  __construct() {   
        parent::__construct();    
    } 
    
    public function index(){
        $this->display();
    }
    
    /**
     * 获取商品分类列表
     */
    public function goodsCategoryList(){        
        $parent_id = I("parent_id", 0, 'intval');
        
        $goodsCategoryList = M('GoodsCategory')->where("parent_id = $parent_id AND is_show=1")->order("sort_order desc,parent_id_path")->select();
        foreach ($goodsCategoryList as $key => $value) {
           $goodsCategoryList[$key]['image'] = parseMediaUrl($value['image']);
            $goodsCategoryList[$key]['home_image'] = parseMediaUrl($value['home_image']);
           if($parent_id == 0){
               $childCategoryList = M('GoodsCategory')->where(array('parent_id' =>$value['id'], ['is_show']=>1))
                   ->order("sort_order desc,parent_id_path")->limit(8)->select();
               $all = $value;
               $all['name'] = '全部';
               $all['mobile_name'] = '全部';
               $all['image'] = parseMediaUrl($value['image']);
               $all['home_image'] = parseMediaUrl($value['home_image']);
               $goodsCategoryList[$key]['child'][] = $all;
               foreach($childCategoryList as $value2){
                   $value2['image'] = parseMediaUrl($value2['image']);
                   $value2['home_image'] = parseMediaUrl($value2['home_image']);
                   $goodsCategoryList[$key]['child'][] = $value2;
               }
           }
        }
        $json_arr = array('status'=>1,'msg'=>'获取成功','result'=>$goodsCategoryList );
        $json_str = json_encode($json_arr);            
        exit($json_str);
    }
    
    /**
     * 获取根据一级分类获取对应的二三级分类
     */
    public function goodsSecAndThirdCategoryList(){
       
        $parent_id = I("parent_id",0); 
     // SELECT * FROM `tp_goods_category` WHERE parent_id_path LIKE '%0\_1\_%'
      /** 一次查询所有二级和三级分类  **/
        
        /*$test_str = 'POST'.print_r($_POST,true);
        $test_str .= 'GET'.print_r($_GET,true);
        file_put_contents('D:\temp\a.html', $test_str);*/
        $list = M('GoodsCategory')->where("parent_id_path LIKE '%0\\_{$parent_id}\\_%' AND is_show=1")->order('sort_order desc')->getField('id,mobile_name,image,level,parent_id');
        $list2 = array();
        foreach ($list as $k =>$v )
        {        
                if($v['level'] == 3)
                    continue;
                
                $arr = array();
                $arr['mobile_name'] = $v['mobile_name'];
                $arr['image'] = parseMediaUrl($v['image']);
                $arr['id'] = $v['id'];
                $arr['level'] = $v['level'];
                $arr['parent_id'] = $v['parent_id'];
                
                $arr3 = array();            
                foreach ($list as $k2 => $v2){
                    if($v['id'] == $v2['parent_id']){
                        $arr3['mobile_name'] = $v2['mobile_name'];
                        $arr3['image'] = parseMediaUrl($v2['image']);
                        $arr3['id'] = $v2['id'];
                        $arr3['level'] = $v2['level'];
                        $arr3['parent_id'] = $v2['parent_id'];
                       $arr['sub_category'][] = $arr3;
                    }
                }  
                //var_dump($arr3);
                
                $list2[] =$arr;
        } 
        
        $json_arr = array('status'=>1,'msg'=>'获取成功','result'=>$list2 );
        $json_str = json_encode($json_arr);
        exit($json_str);
    }
    
    
    /**
     * 商品列表页
     */
    public function goodsList(){
    	// 返回给手机app 生成路径格式 为 普通 index.php?=api&c=  最普通的路径格式
        $p = I('p', 1, 'intval');
        $filter_param = array(); // 帅选数组                        
        $id = I('id',1); // 当前分类id 
        // $shop_id = I('shop_id',0); // 当前店铺 
        $brand_id = I('brand_id',0); //品牌id
        $spec = I('spec',0); // 规格 
        $attr = I('attr',''); // 属性        
        $sort = I('sort','goods_id'); // 排序
        $sort_asc = I('sort_asc','asc'); // 排序
        $price = I('price',''); // 价钱
        $start_price = trim(I('start_price','0')); // 输入框价钱
        $end_price = trim(I('end_price','0')); // 输入框价钱        
    	if($start_price && $end_price) $price = $start_price.'-'.$end_price; // 如果输入框有价钱 则使用输入框的价钱   	 
    	$filter_param['id'] = $id; //加入筛选条件中
    	$brand_id  && ($filter_param['brand_id'] = $brand_id); //加入帅选条件中
    	$spec  && ($filter_param['spec'] = $spec); //加入帅选条件中
    	$attr  && ($filter_param['attr'] = $attr); //加入帅选条件中
    	$price  && ($filter_param['price'] = $price); //加入帅选条件中

        $pagesize = I('pagesize', 10, 'intval');
         
    	$goodsLogic = new GoodsLogic(); // 前台商品操作逻辑类
    	// 分类菜单显示
    	$goodsCate = M('GoodsCategory')->where("id = $id")->find();// 当前分类
    	//($goodsCate['level'] == 1) && header('Location:'.U('Home/Channel/index',array('cat_id'=>$id))); //一级分类跳转至大分类馆
    	$cateArr = $goodsLogic->get_goods_cate($goodsCate);
    	 
    	// 帅选 品牌 规格 属性 价格
    	$cat_id_arr = getCatGrandson ($id);

    	$filter_goods_id = M('goods')->where("is_on_sale=1 and cat_id in(".  implode(',', $cat_id_arr).") ")->getField("goods_id",true);

    	// 过滤帅选的结果集里面找商品
    	if($brand_id || $price)// 品牌或者价格
    	{
    		$goods_id_1 = $goodsLogic->getGoodsIdByBrandPrice($brand_id,$price); // 根据 品牌 或者 价格范围 查找所有商品id
    		$filter_goods_id = array_intersect($filter_goods_id,$goods_id_1); // 获取多个帅选条件的结果 的交集
    	}
    	if($spec)// 规格
    	{
    		$goods_id_2 = $goodsLogic->getGoodsIdBySpec($spec); // 根据 规格 查找当所有商品id
    		$filter_goods_id = array_intersect($filter_goods_id,$goods_id_2); // 获取多个帅选条件的结果 的交集
    	}
    	if($attr)// 属性
    	{
    		$goods_id_3 = $goodsLogic->getGoodsIdByAttr($attr); // 根据 规格 查找当所有商品id
    		$filter_goods_id = array_intersect($filter_goods_id,$goods_id_3); // 获取多个帅选条件的结果 的交集
    	}
    	 
    	$filter_menu  = $goodsLogic->get_filter_menu($filter_param,'goodsList'); // 获取显示的帅选菜单
    	$filter_price = $goodsLogic->get_filter_price($filter_goods_id,$filter_param,'goodsList'); // 帅选的价格期间
    	$filter_brand = $goodsLogic->get_filter_brand($filter_goods_id,$filter_param,'goodsList',1); // 获取指定分类下的帅选品牌
    	//$filter_spec  = $goodsLogic->get_filter_spec($filter_goods_id,$filter_param,'goodsList',1); // 获取指定分类下的帅选规格
    	$filter_attr  = $goodsLogic->get_filter_attr($filter_goods_id,$filter_param,'goodsList',1); // 获取指定分类下的帅选属性
    	
    	$count = count($filter_goods_id);
    	if($count > 0)
    	{
            $sortStr = "$sort $sort_asc";
    		$goods_list = M('goods')
                ->field('goods_id,cat_id,goods_sn,goods_name,goods_remark,shop_price,market_price,comment_count,original_img')
                ->where("goods_id in (".  implode(',', $filter_goods_id).")")
                ->order(empty($sortStr)?"on_time desc":$sortStr.",on_time desc")
                ->page($p, $pagesize)->select();
            foreach( $goods_list as $k => &$goods_listv )
            {
                $goods_listv['original_img'] = parseMediaUrl($goods_listv['original_img']);
            }
    		$filter_goods_id2 = get_arr_column($goods_list, 'goods_id');
    	}
    	//$goods_category = M('goods_category')->where('is_show=1')->cache(true)->getField('id,name,parent_id,level'); // 键值分类数组
    	$goods_category = M('goods_category')->where('is_show=1')->getField('id,name,parent_id,level'); // 键值分类数组
    	$list['goods_list'] = $goods_list ? $goods_list : [];
        $list['count'] = $count;
        $i = 1;
    	//菜单
        foreach($filter_menu as $k => $v) // 依照app端的要求 去掉 键名
        {
            $v['name'] = $v['text'];
            unset($v['text']);
            $list['filter_menu'][] = $v;  // 帅选规格
        }
        
        // $list['filter_spec'] = $filter_spec;
        // 属性
        foreach($filter_attr as $k => $v) // 依照app端的要求 去掉 键名
        {           
            $items['name'] = $v['attr_name'];
            foreach($v['attr_value'] as $k2 => $v2)
            {
            $items['item'][] = array('name'=>$v2['attr_value'],'href'=>$v2['href'],'id'=>$i++);
            }
           
            $list['filter_attr'][] = $items;
            $items = array();
        }                
        // 品牌
        foreach($filter_brand as $k => $v) // 依照app端的要求 去掉 键名
        {                                              
            $list['filter_brand'][] = array('name'=>$v['name'],'href'=>$v['href'],'id'=>$i++);
        }                    
        // 价格
        foreach($filter_price as $k => $v) // 依照app端的要求 去掉 键名
        {                                              
            $list['filter_price'][] = array('name'=>$v['value'],'href'=>$v['href'],'id'=>$i++);
        }
        
        $list['sort'] =  $sort;
        $list['sort_asc'] =  $sort_asc;
    	$sort_asc = $sort_asc == 'asc' ? 'desc' : 'asc';        
        $list['orderby_default'] = urldecode(U("Goods/goodsList",$filter_param,'')); // 默认排序
        $list['orderby_sales_sum'] = urldecode(U("Goods/goodsList",array_merge($filter_param,array('sort'=>'sales_sum','sort_asc'=>'desc')),'')); // 销量排序
        $list['orderby_price'] = urldecode(U("Goods/goodsList",array_merge($filter_param,array('sort'=>'shop_price','sort_asc'=>$sort_asc)),'')); // 价格
        $list['orderby_comment_count'] = urldecode(U("Goods/goodsList",array_merge($filter_param,array('sort'=>'comment_count','sort_asc'=>'desc')),'')); // 评论
        $list['orderby_is_new'] = urldecode(U("Goods/goodsList",array_merge($filter_param,array('sort'=>'is_new','sort_asc'=>'desc')),'')); // 新品
    	C('TOKEN_ON',false);
        
        $json_arr = array('status'=>1,'msg'=>'获取成功','result'=>$list );
        $json_str = json_encode($json_arr,true);            
        exit($json_str);
    }    

     /**
     * 商品搜索列表页
     */
    public function search(){
    	
        C('URL_MODEL',0); // 返回给手机app 生成路径格式 为 普通 index.php?=api&c=  最普通的路径格式
    	$filter_param = array(); // 帅选数组
        $p = I('get.p',1 ,'intval');
    	$id = I('get.id',0); // 当前分类id
    	$brand_id = I('brand_id',0);    	    	
    	$sort = I('sort','goods_id'); // 排序
    	$sort_asc = I('sort_asc','asc'); // 排序
    	$price = I('price',''); // 价钱
    	$start_price = trim(I('start_price','0')); // 输入框价钱
    	$end_price = trim(I('end_price','0')); // 输入框价钱
    	if($start_price && $end_price) $price = $start_price.'-'.$end_price; // 如果输入框有价钱 则使用输入框的价钱   	 
    	$filter_param['id'] = $id; //加入帅选条件中
    	$brand_id  && ($filter_param['brand_id'] = $brand_id); //加入帅选条件中    	    	
    	$price  && ($filter_param['price'] = $price); //加入帅选条件中
        $q = urldecode(trim(I('q',''))); // 关键字搜索
        $q  && ($_GET['q'] = $filter_param['q'] = $q); //加入帅选条件中
        if(empty($q))
            exit(json_encode(array('status'=>-1,'msg'=>'请输入搜索关键词'),true));            
        
    	$goodsLogic = new GoodsLogic(); // 前台商品操作逻辑类
    	//$filter_goods_id = M('goods')->where("is_on_sale=1 and goods_name like '%{$q}%'  ")->cache(true)->getField("goods_id",true);
    	$filter_goods_id = M('goods')->where("is_on_sale=1 and goods_name like '%{$q}%'  ")->getField("goods_id",true);

    	// 过滤帅选的结果集里面找商品
    	if($brand_id || $price)// 品牌或者价格
    	{
    		$goods_id_1 = $goodsLogic->getGoodsIdByBrandPrice($brand_id,$price); // 根据 品牌 或者 价格范围 查找所有商品id
    		$filter_goods_id = array_intersect($filter_goods_id,$goods_id_1); // 获取多个帅选条件的结果 的交集
    	}
    	  
    	$filter_menu  = $goodsLogic->get_filter_menu($filter_param,'search'); // 获取显示的帅选菜单
    	$filter_price = $goodsLogic->get_filter_price($filter_goods_id,$filter_param,'search'); // 帅选的价格期间
    	$filter_brand = $goodsLogic->get_filter_brand($filter_goods_id,$filter_param,'search',1); // 获取指定分类下的帅选品牌    	 
    	
    	$count = count($filter_goods_id);
    	$page = new Page($count,10);
    	if($count > 0)
    	{
            $goods_list = M('goods')
                ->field('goods_id,cat_id,goods_sn,goods_name,shop_price,comment_count')
                ->where("goods_id in (".  implode(',', $filter_goods_id).")")
                ->order("$sort $sort_asc".",on_time desc")
                ->page($p, 10)
                ->select();
    		$filter_goods_id2 = get_arr_column($goods_list, 'goods_id');
    	}
    	//$goods_category = M('goods_category')->where('is_show=1')->cache(true)->getField('id,name,parent_id,level'); // 键值分类数组
    	$goods_category = M('goods_category')->where('is_show=1')->getField('id,name,parent_id,level'); // 键值分类数组

    	$list['goods_list'] = $goods_list;
    	 
        $i = 1;
    	//菜单
        foreach($filter_menu as $k => $v) // 依照app端的要求 去掉 键名
        {
            $v['name'] = $v['text'];
            unset($v['text']);
            $list['filter_menu'][] = $v;  // 帅选规格
        }
      
        // 品牌
        foreach($filter_brand as $k => $v) // 依照app端的要求 去掉 键名
        {                                              
            $list['filter_brand'][] = array('name'=>$v['name'],'href'=>$v['href'],'id'=>$i++);
        }        
                    
        // 价格
        foreach($filter_price as $k => $v) // 依照app端的要求 去掉 键名
        {                                              
            $list['filter_price'][] = array('name'=>$v['value'],'href'=>$v['href'],'id'=>$i++);
        }
        
        $list['sort'] =  $sort;
        $list['sort_asc'] =  $sort_asc;
    	$sort_asc = $sort_asc == 'asc' ? 'desc' : 'asc';        
        $list['orderby_default'] = urldecode(U("Goods/search",$filter_param,'')); // 默认排序
        $list['orderby_sales_sum'] = urldecode(U("Goods/search",array_merge($filter_param,array('sort'=>'sales_sum','sort_asc'=>'desc')),'')); // 销量排序
        $list['orderby_price'] = urldecode(U("Goods/search",array_merge($filter_param,array('sort'=>'shop_price','sort_asc'=>$sort_asc)),'')); // 价格
        $list['orderby_comment_count'] = urldecode(U("Goods/search",array_merge($filter_param,array('sort'=>'comment_count','sort_asc'=>'desc')),'')); // 评论
        $list['orderby_is_new'] = urldecode(U("Goods/search",array_merge($filter_param,array('sort'=>'is_new','sort_asc'=>'desc')),'')); // 新品
    	C('TOKEN_ON',false);
        
        $json_arr = array('status'=>1,'msg'=>'获取成功','result'=>$list );
        $json_str = json_encode($json_arr,true);
        exit($json_str);        
    }    
    
    /**
     * 获取商品详情
     */
    public function goodsInfo(){

        $user_id = $this->user_id;        
        $goods_id = I('id', 1, 'intval');
        $where['goods_id'] = $goods_id;
        $model = M('Goods');
        $goods  = $model->where($where)->find();
        if (!$goods) {
            $this->returnInfo('-1','该商品不存在');
        }
        $kill['goods_id'] = $goods_id;
        $kill['is_end'] = 0;
        $kill_info = M('flash_sale')->field('price,buy_num,start_time,end_time')->where($kill)->find();
        if ($kill_info) {
            $goods['shop_price'] = $kill_info['price'];
            $goods['start_time'] = $kill_info['start_time'];
            $goods['end_time']   = $kill_info['end_time'];
            $goods['sales_sum']  = $kill_info['buy_num'];
            $goods['is_kill']    = 1;
        }else{
            $goods['sales_sum']  = $goods['sales_sum'];
            $goods['shop_price'] = $goods['shop_price'];
        }
        $goods['collect_num'] = $goods['collect_num']?$goods['collect_num']:0;
        $is_collect = M('GoodsCollect')->where("user_id=$user_id and goods_id=$goods_id")->find();
        if (!empty($is_collect)) {
           $goods['is_collect'] = 1;
        }else{
            $goods['is_collect'] = 0;
        }
        // 处理商品规格
        // 商品规格 价钱 库存表 找出 所有 规格项id
        $keys = M('SpecGoodsPrice')->where("goods_id = $goods_id")->getField("GROUP_CONCAT(`key` SEPARATOR '_') ");
        $goods_attr_list = M('GoodsAttr as g')
                        ->field('ga.attr_id,ga.attr_name,g.attr_value')
                        ->join('ln_goods_attribute as ga on ga.attr_id=g.attr_id')
                        ->where([
                            'goods_id' => $goods_id
                        ])
                        ->select(); 
        $goods['goods_attr_list'] = $goods_attr_list?$goods_attr_list:array();
        
        if($keys)
        {
            $specImage = M('SpecImage')->where("goods_id = $goods_id and src != '' ")->getField("spec_image_id,src");// 规格对应的 图片表， 例如颜色
            $keys = explode("_",$keys);
            $keys = array_unique($keys);
            $keys = implode(',',$keys);
            $filter_spec2 = M("SpecItem")->alias("a")
                            ->join("ln_spec AS b ON b.id = a.spec_id")
                            ->where([
                                "a.id" => ["IN",$keys]
                            ])
                            ->field("b.name,b.order,a.*")
                            ->order("a.spec_id,b.id")
                            ->fetchSql(0)
                            ->select();
            $filter_spec = [];
            foreach($filter_spec2 as $val){
                if(!array_key_exists($val['name'],$filter_spec)){
                    $filter_spec[$val['name']]['name'] = $val['name'];
                }
                $filter_spec[$val['name']]['values'][] = [
                    'item'=> $val['item'],
                    'item_id'=> $val['id'],
                    'src' =>$specImage[$val['id']] ? parseMediaUrl($specImage[$val['id']]) : ''
                ];
            }

            $goods_spec_list = array_values($filter_spec);
            $goods['goods_spec_list'] = $goods_spec_list?$goods_spec_list:array();
        }
        #理论上此处应该使用正则处理
        $goods['goods_content'] = parseRichTextContent($goods['goods_content']);
        $goods['original_img'] = parseMediaUrl($goods['original_img']);
        //获取实际评论数
        $goods['comment_count'] = M('comment')->where("goods_id={$goods_id} AND is_show=1 AND parent_id=0")->count();
        $return['goods'] = $goods;
        $spec_goods_price = M('spec_goods_price')->field("key,price,store_count")->where("goods_id = $goods_id")->select();// 规格 对应 价格 库存表
        $return['spec_goods_price'] = $spec_goods_price ? $spec_goods_price : array();
        $return['gallery'] = M('goods_images')->field('image_url')->where(array('goods_id'=>$goods_id))->select();
        foreach($return['gallery'] as $key => $val){
           $return['gallery'][$key]['image_url'] = parseMediaUrl($return['gallery'][$key]['image_url']);
        }
        $return['gallery']?$return['gallery']:[];
        $goodsLogic = new GoodsLogic();
        $add_update_info = $goodsLogic->addgoodsView($user_id, $goods_id);
        //获取最近的两条评论
        $latest_comment = M('comment')->where("goods_id={$goods_id} AND is_show=1 AND parent_id=0")->limit(2)->select();
        // 月销量
        $return['goods']['sales_sum'] = M('order_goods')
                            ->alias('g')
                            ->join('ln_order o on o.order_id=g.order_id')
                            ->where([
                                'g.goods_id' => $goods_id,
                                'o.add_time' => ['GT', strtotime('-31 days')],
                                'o.pay_status' => ['GT',0]
                            ])->fetchSql(0)->sum('g.goods_num');
        $return['goods']['sales_sum'] = $return['goods']['sales_sum'] ? $return['goods']['sales_sum'] : 0;
        foreach($latest_comment as $k => &$v)
        {
            $v['img'] = unserialize($v['img']);
            if(!empty($v['img']))
            {
                foreach($v['img'] as &$item)
                {
                    $item = parseMediaUrl($item);
                }
            }else{
                $v['img'] = [];
            }
        }
        $return['comment'] = $latest_comment ? $latest_comment : [];

        // 输出客服
        $return['shop_kefu'] = '';
        if( !empty($return['goods']) )
        {
            $shop = M('shop')->where([
                "id" => $return['goods']['shop_id']
            ])->field('id as shop_id,user_id')->find();
            if( $shop )
            $return['shop_kefu'] = $shop['user_id'];
            $return['shop_kefu_info'] = M('users')->where([
                'user_id' => $shop['user_id']
            ])->field('user_id,nickname,head_pic')->find();
            if(  $return['shop_kefu_info'] )
            {
                $return['shop_kefu_info']['head_pic'] = \parseMediaUrl($return['shop_kefu_info']['head_pic'] );
            }else{
                $return['shop_kefu_info'] = '';
            }
        }
        
        $this->returnInfo(1,'获取成功',$return);

    }
     /**
     * 获取用户浏览记录
     */
    public function goodsView(){ 
        if(!$this->user_id){
            exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
        }
        $p = I('p', 1, 'intval');
        $goodsLogic = new GoodsLogic();
        $goodsViewInfo = $goodsLogic->goodsView($this->user_id, $p);
        $json_arr = array('status'=>1,'msg'=>'获取成功','result'=>$goodsViewInfo);
        $json_str = json_encode($json_arr);            
        exit($json_str);
    }

     /**
     * 浏览记录 插入
     */
    public function addgoodsView(){
        $goods_id = I('id', 0, 'intval');
        if(!$this->user_id){
            exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
        }
        if(!$goods_id){
            exit(json_encode(array('status'=>-2,'msg'=>'缺少参数','result'=>'')));
        }
        $goodsLogic = new GoodsLogic();
        $add_update_info = $goodsLogic->addgoodsView($this->user_id, $goods_id);

        if($add_update_info['is_success']){
            exit(json_encode(array('status'=>1,'msg'=>$add_update_info['message'],'result'=>'')));
        } else {
            exit(json_encode(array('status'=>-1,'msg'=>$add_update_info['message'],'result'=>'')));
        }
    }
	
	/*
	 * 获取热销分类数据
	 */
	public function goodsFineCategoey(){
	    //获取大分类
	    $category_arr = M('goods_category')->where('parent_id=0 and is_hot = 1 and is_show = 1')->field('id,mobile_name,image')->order('sort_order desc')->limit(9)->select();
	    $result = array();
	    foreach($category_arr as $c){
	        $c['image'] = parseMediaUrl($c['image']);      
	        $result[] = $c;
	    }
	
	    exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>array('category'=>$result))));
	}


	
	 /**
	 *  获取首页商品的精品 热销 积分兑换 数据
	 */  
	public function goodsFine()
	{
	   $type = I('post.type');
	   $map['is_on_sale'] = 1;
	   if(I('post.cat_id')){
		   $cat_id = I('post.cat_id');
		   // 获取当前分类id是否是第一分类
		   $goods_category = M('goods_category')->where(['id'=>$cat_id,'parent_id'=>0])->find();
		   if($goods_category){
			   $where_goods_category_list['parent_id_path'] = ['like','0\_'.$cat_id.'\_%'];
			   $goods_category_list = M('goods_category')->field('id')->where($where_goods_category_list)->select();
			   $cat_id_str = '';
			   foreach($goods_category_list as $k => $v){
				   $cat_id_str .= $v['id'].',';
			   }
			   $map['cat_id'] = ['in',$cat_id_str];
		   }else{
			   $map['cat_id'] = $cat_id;
		   }
	   }
	   $list = array();
	   switch ($type) {
	       case '1':
	           $map['is_recommend'] = 1;  // 推荐
	           break;
	       case '2':
	           $map['is_new'] = 1;   // 新品
	           break;
	       case '3':
	           $map['is_hot'] = 1;  // 热销
	           break;               
	       case '4':
	           $map['exchange_integral'] = ['EGT',1];  // 积分兑换
	           break;               
	       default:
	           exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>$list )));
	   }
	    $count = M('goods')->where($map)->count();
	    $_GET['p'] = $_REQUEST['p'];
	    $p = I('p', 1, 'intval');
	    $page = new Page($count,10);
	    $list = M('goods')->field('exchange_integral,is_recommend,is_new,is_hot,goods_remark,goods_id,cat_id,goods_sn,goods_name,market_price,shop_price,comment_count,original_img')
	                      ->where($map)->order("sort desc,on_time desc")->page($p, 10)->select();
		foreach($list as $k => &$v)
		{
		    $v['original_img'] = parseMediaUrl( $v['original_img'] );
			$point_ex_rate = tpCache('shopping.point_rate');//积分兑换比例
			$v['integral_money'] = $v['exchange_integral'] / $point_ex_rate;//积分可抵扣金额
		}
	    exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$list )));
	}
    /**
     *  获取商品的缩略图
     */
    function goodsThumImages()
    {        
        $goods_id = I('goods_id');
        $width = I('width');
        $height = I('height');         
        $img_url = parseMediaUrl(goods_thum_images($goods_id,$width,$height));                
        $image = file_get_contents($img_url);  //假设当前文件夹已有图片001.jpg        
        header('Content-type: image/jpg');
        exit($image);
    }
    
    
    /**
     * 获取某个商品的评价
     */
    public function getGoodsComment(){
        $goods_id = I('post.goods_id', 0, 'intval');
         if(!$goods_id){
             exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
         }
        $where['goods_id'] = $goods_id;
        $where['is_show'] = 1;          //是否显示
        $where['parent_id'] =0;         //区分评论与咨询

        $p = I('post.p', 1, 'intval');  //页码
        $list = M('comment')->alias('a')->join('ln_users as b on b.user_id = a.user_id','left')
        ->field('comment_id,goods_id,a.email,username,content,deliver_rank,add_time,ip_address,is_show,a.user_id,img,order_id,goods_rank,service_rank,b.head_pic')
        ->where($where)->order("a.comment_id desc")->page($p,10)->select();
        if(empty($list)){
            exit(json_encode(array('status'=>1,'msg'=>'数据为空','result'=>[])));
        }else{
            foreach ($list as $k => &$val) {
                // $head_pic = M('users')->field('head_pic')->where(array('user_id'=>$val['user_id']))->find();
                //获取商家评论
                $replyList = M('Comment')->field('username,content')->where(array('is_show' => 1, 'goods_id' => $goods_id, 'parent_id' => $val['comment_id'] ))->order("add_time desc")->select();
                foreach ($replyList as $key => &$value) {
                    $value['username']= $value['username']?$value['username']:"";
                    $value['content']= $value['content']?$value['content']:"";
                }
                $val['reply_list'] = $replyList;
                $val['order_id'] = $val['order_id']?$val['order_id']:0;
                $val['head_pic'] = parseMediaUrl($val['head_pic']);

                $val['img'] = unserialize($val['img']);

                //获取评论图片
                if(empty($val['img']))
                {
                    $val['img'] = [];
                    continue;
                }

                foreach ($val['img'] as &$vv)
                {
                    if( empty($vv) )
                    {
                        unset($vv);
                    }else{
                        $vv = parseMediaUrl($vv);
                    }
                    
                }
            }
            $this->returnInfo('1','获取成功',$list);
        }
        
    }
    /**
     * 收藏商品与取消收藏
     */
    public function collectGoods(){
        $goods_id = I('goods_id');
        $type = I('type',0);
        $count = M('Goods')->where("goods_id = $goods_id")->count();
		
        if($count == 0) 
            $this->returnInfo('-1','收藏商品不存在',[]);
        //删除收藏商品
        if($type==1){
            M('GoodsCollect')->where("user_id = {$this->user_id} and goods_id = $goods_id")->delete();
            exit(json_encode(array('status'=>1,'msg'=>'成功取消收藏','result'=>'-1' )));
        }
        $count = M('GoodsCollect')->where("user_id = {$this->user_id} and goods_id = $goods_id")->count();
        if($count > 0)        exit(json_encode(array('status'=>1,'msg'=>'您已收藏过该商品','result'=>'1' )));
        M('GoodsCollect')->add(array(
            'goods_id'=>$goods_id,
            'user_id'=>$this->user_id,
            'add_time'=>time(),
        ));
        //更新收藏数量
        M('GoodsCollect')->where("good_id=$goods_id")->setInc('collect_num');
        exit(json_encode(array('status'=>1,'msg'=>'收藏成功','result'=>'1')));
    }


    /**
     * 批量取消商品收藏
     * create by dulong
     */
    public function cancel_collectgoods(){
        $ids = I('ids', ''); // 逗号分隔的ids
        $info = $this->cancelAllFavorite($ids);
        exit(json_encode(array('status'=>1,'msg'=>'取消收藏成功!','result'=>$info)));
    }

    /**
     * 批量取消收藏
     * @param $ids
     * @return array
     */
    public function cancelAllFavorite($ids){
        if(!$ids){
            exit(json_encode(array('status'=>-1,'msg'=>'数据丢失, 未知错误','result'=>'')));
        }

        $arr_favorite_id = explode(',', $ids);
        $goodsModel = M('GoodsCollect');
        foreach ($arr_favorite_id as $value){
            $where['collect_id'] = $value;
            $goodsModel->where($where)->delete();
        }
        exit(json_encode(array('status'=>1,'msg'=>'取消收藏成功!','result'=>'-1')));
    }

    

    
    
    /**
     * 猜你喜欢/热门推荐
     */
    public function guessYouLike(){
        $p = I('p', 1, 'intval');
        $favourite_goods = M('goods')->where("is_recommend=1 and is_on_sale=1")->order('goods_id DESC')->page($p,10)->getField('goods_id,cat_id,goods_sn,goods_name,original_img,market_price,shop_price,comment_count,goods_remark');//首页/购物车/我的 推荐商品
        $goods = array();
    	foreach ($favourite_goods as $k => $v){
			$v['original_img'] = parseMediaUrl($v['original_img']);
    	    $goods[] = $v;
    	}
    	$json_arr = array('status'=>1,'msg'=>'获取成功','result'=>$goods );
    	$json_str = json_encode($json_arr,true);
    	
    	exit($json_str);
    }

    /**
     * 删除浏览记录
     */
    // public function del_goods_history(){
    //     $goods_history_id = I('id', 0, 'intval');
    //     if(!$this->user_id){
    //         exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
    //     }
    //     if(!$goods_history_id){
    //         exit(json_encode(array('status'=>-2,'msg'=>'缺少参数','result'=>'')));
    //     }
    //     $goodsLogic = new GoodsLogic();
        // $update_info = $goodsLogic->del_goods_history($goods_history_id);
    //     if($update_info['is_success']){
    //         exit(json_encode(array('status'=>1,'msg'=>$update_info['message'],'result'=>'')));
    //     }else{
    //         exit(json_encode(array('status'=>-1,'msg'=>$update_info['message'],'result'=>'')));
    //     }
    // }


    /**
     * 删除商品浏览记录
     * create by dulong
     */
    public function del_goods_history(){
        $ids = I('ids', ''); // 逗号分隔的ids
        $user_id = $this->user_id;
        $info = $this->cancelAllhistory($ids,$user_id);
        exit(json_encode(array('status'=>1,'msg'=>'删除成功!','result'=>$info)));
    }

    /**
     * 批量
     * @param $ids
     * @return array
     */
    public function cancelAllhistory($ids,$user_id){
        if(!$ids){
            exit(json_encode(array('status'=>-1,'msg'=>'数据丢失, 未知错误','result'=>'')));
        }
        $arr_favorite_id = explode(',', $ids);
        $goodsModel = M('goods_history');
        foreach ($arr_favorite_id as $value){
            $where['goods_id'] = $value;
            $goodsModel->where($where)->delete();
        }
        $this->returnInfo('1','删除成功');
    }

    
}